package de.sono.radio.parser;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.util.ByteArrayBuffer;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.util.Log;
import de.sono.radio.list.RadioStation;

public class HTMLParser {

	public List<RadioStation> getStations(String pUrl)
			throws IOException {

		Document doc = Jsoup.connect(pUrl).get();

		ArrayList<RadioStation> stations = new ArrayList<RadioStation>();

		Elements items = doc.getElementsByTag("li");

		String imgUrl;
		String streamUrl;
		String streamName;
		String streamInfo;
		byte[] imgData;

		for (Element li : items) {
			Elements img = li.getElementsByTag("img");
			imgUrl = img.get(0).attr("src");

			Element a = li.getElementsByTag("a").get(1);
			streamUrl = a.attr("href");
			streamName = a.text();

			Element p = li.getElementsByTag("p").get(0);
			streamInfo = p.text();

			imgData = getImg(imgUrl);

			stations.add(new RadioStation(streamName, streamInfo, streamUrl,
					imgUrl, imgData));
		}

		return stations;
	}

	private byte[] getImg(String pUrl) {

		try {
			URL url = new URL(pUrl);

			// long startTime = System.currentTimeMillis();
			// Log.d("ImageManager", "download begining");
			// Log.d("ImageManager", "download url:" + url);
			// Log.d("ImageManager", "downloaded file name:" + fileName);
			/* Open a connection to that URL. */
			URLConnection ucon = url.openConnection();

			/*
			 * Define InputStreams to read from the URLConnection.
			 */
			InputStream is = ucon.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);

			/*
			 * Read bytes to the Buffer until there is nothing more to read(-1).
			 */
			ByteArrayBuffer baf = new ByteArrayBuffer(50);
			int current = 0;
			while ((current = bis.read()) != -1) {
				baf.append((byte) current);
			}

			/* Convert the Bytes read to a String. */
			return baf.toByteArray();

		} catch (IOException e) {
			Log.d("HTMLParser IMG Download", "Error: " + e);
		}
		return null;
	}
}
